package com.example.service.impl;

import com.example.channel.BootNettyClientChannel;
import com.example.channel.BootNettyClientChannelCache;
import com.example.instance.BootNettyClient;
import com.example.service.HeartBeatService;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @ClassName: HeartBeatServiceImpl
 * @Author : 13736
 * @Date :2023/7/8  23:28
 * @Description: TODO
 * @Version :1.0
 */
@Slf4j
@Service
public class HeartBeatServiceImpl implements HeartBeatService {

    @Autowired
    private BootNettyClient bootNettyClient;

    @Scheduled(cron = "0/30 * * * * ?")
    @Override
    public void heartBeatCheck() {
        String back = "heartbeat......";
        if (BootNettyClientChannelCache.channelMapCache.size() > 0) {
            log.info("Heartbeat detection...");
            for (Map.Entry<String, BootNettyClientChannel> entry : BootNettyClientChannelCache.channelMapCache.entrySet()) {
                BootNettyClientChannel bootNettyChannel = entry.getValue();
                if (bootNettyChannel != null && bootNettyChannel.getChannel().isOpen()) {
                    bootNettyChannel.getChannel().writeAndFlush(Unpooled.buffer().writeBytes(back.getBytes()));
                }
            }
        }else {
            reconnect();
        }
    }


    @Override
    public void reconnect() {
        log.info("Attempting to reconnect......");
        try {
            bootNettyClient.connect();
        } catch (Exception e) {
            log.info("Reconnection failed.",e);
        }
    }

}
